//
//  ChatViewController.m
//  Gabber
//
//  Created by 陆惠国 on 11-8-26.
//  Copyright 2011年 恒生聚源. All rights reserved.
//

#import "ChatViewController.h"
#import "XMPPClient.h"

#import "Message.h"
#import "RosterTitleView.h"

#define CHAT_BACKGROUND_COLOR [UIColor colorWithRed:0.859f green:0.886f blue:0.929f alpha:1.0f]
#define SENT_DATE_TAG 101
#define TEXT_TAG 102
#define BACKGROUND_TAG 103
#define AVATAR_TAG 104

#define SECONDS_BETWEEN_MESSAGES        (60*15)

static CGFloat const kSentDateFontSize = 13.0f;
static CGFloat const kAvatarSize = 40.0f;
static CGFloat const kMessageFontSize   = 16.0f;   // 15.0f, 14.0f
static CGFloat const kMessageTextWidth  = 180.0f;
static CGFloat const kContentHeightMax  = 84.0f;  // 80.0f, 76.0f

static CGFloat const kChatBarHeight1    = 40.0f;
static CGFloat const kChatBarHeight4    = 94.0f;

@implementation ChatViewController


@synthesize jidStr = _jidStr;
@synthesize items = _items;
@synthesize fetchedResultsController = _fetchedResultsController;

@synthesize titleView = _titleView;
@synthesize contentView = _contentView;
@synthesize chatContent = _chatContent;
@synthesize chatHeaderView = _chatHeaderView;
@synthesize chatBar = _chatBar;
@synthesize chatInput = _chatInput;
@synthesize sendButton = _sendButton;
@synthesize clearHistoryButton = _clearHistoryButton;
@synthesize loadHistoryButton = _loadHistoryButton;
@synthesize leftBubble = _leftBubble;
@synthesize rightBubble = _rightBubble;
@synthesize myAvatar = _myAvatar;
@synthesize avatar = _avatar;
@synthesize lastDate = _lastDate;
@synthesize showHistory = _showHistory;
@synthesize active = _active;


@synthesize facialButton=_facialButton;
@synthesize scrollView=_scrollView;

@synthesize sendfaceArray=_sendfaceArray;
@synthesize receivefaceArray=_receivefaceArray;

@synthesize facialPopover=_facialPopover;

#pragma mark - Init/dealloc
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.hidesBottomBarWhenPushed = YES;      
        self.title = @"聊天";   
        //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(closeAction)] autorelease];
        
        
        self.showHistory = NO;
        self.lastDate = [XMPPClient sharedInstance].lastLoginDate;
        
        if(TTIsPad()){
            [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleSettingsChanged:) name: kSettingsChangedNotification object: nil]; 
        }
        
        NSArray* receiveArr = [NSArray arrayWithObjects:@">:o",@":-[",@";-)",@"B-)",@":'(",@"]:)",@":-D",@":-)",@":^0",@":x",@";\\",@":-(",@":-p",@"?:|",@":0",@":|",@"(!)",@"(i)",@"(+)",@"(-)",@"(heart)",nil];
        
        NSArray*  sendArr = [NSArray arrayWithObjects:@"\uE416",@"\uE401",@"\uE405",@"\uE107",@"\uE411",@"\uE412",@"\uE415",@"\uE056",@"\uE057",@"\uE418",@"\uE410",@"\uE403",@"\uE409",@"\uE020",@"\uE40b",@"\uE40d",@"\uE021",@"\uE022",@"\uE41f",@"\uE00e",@"\uE421",nil];
        
        _receivefaceArray=[[NSMutableArray alloc]initWithArray:receiveArr copyItems:YES];
        _sendfaceArray=[[NSMutableArray alloc]initWithArray:sendArr copyItems:YES];

        
//        _receivefaceArray=[[NSMutableArray alloc]init];
//        
//        [_receivefaceArray addObject:@">:o"];
//        [_receivefaceArray addObject:@":-["];
//        [_receivefaceArray addObject:@";-)"];
//        [_receivefaceArray addObject:@"B-)"];
//        [_receivefaceArray addObject:@":'("];
//        [_receivefaceArray addObject:@"]:)"];
//        [_receivefaceArray addObject:@":-D"];
//        
//        [_receivefaceArray addObject:@":-)"];
//        [_receivefaceArray addObject:@":^0"];
//        [_receivefaceArray addObject:@":x"];
//        [_receivefaceArray addObject:@";\\"];
//        [_receivefaceArray addObject:@":-("];
//        [_receivefaceArray addObject:@":-p"];
//        [_receivefaceArray addObject:@"?:|"];
//        
//        
//        [_receivefaceArray addObject:@":0"];
//        [_receivefaceArray addObject:@":|"];
//        [_receivefaceArray addObject:@"(!)"];
//        [_receivefaceArray addObject:@"(i)"];
//        [_receivefaceArray addObject:@"(+)"];
//        [_receivefaceArray addObject:@"(-)"];
//        [_receivefaceArray addObject:@"(heart)"];
//        
//        _sendfaceArray=[[NSMutableArray alloc]init];
//        
//        [_sendfaceArray addObject:@"\uE416"];
//        [_sendfaceArray addObject:@"\uE401"];
//        [_sendfaceArray addObject:@"\uE405"];
//        [_sendfaceArray addObject:@"\uE107"];
//        [_sendfaceArray addObject:@"\uE411"];
//        [_sendfaceArray addObject:@"\uE412"];
//        [_sendfaceArray addObject:@"\uE415"];
//        
//        
//        [_sendfaceArray addObject:@"\uE056"];
//        [_sendfaceArray addObject:@"\uE057"];
//        [_sendfaceArray addObject:@"\uE418"];        
//        [_sendfaceArray addObject:@"\uE410"];
//        [_sendfaceArray addObject:@"\uE403"];
//        [_sendfaceArray addObject:@"\uE409"];
//        [_sendfaceArray addObject:@"\uE020"];
//        
//        [_sendfaceArray addObject:@"\uE40b"];
//        [_sendfaceArray addObject:@"\uE40d"];
//        [_sendfaceArray addObject:@"\uE021"];        
//        [_sendfaceArray addObject:@"\uE022"];
//        [_sendfaceArray addObject:@"\uE41f"];
//        [_sendfaceArray addObject:@"\uE00e"];
//        [_sendfaceArray addObject:@"\uE421"];
        
    }
    return self;
}

- (id)initWithJidStr:(NSString*)jidStr
{
    if ((self = [self initWithNibName:nil bundle:nil])) {
        self.jidStr = jidStr;
        
    }
    return self;     
}

- (void)dealloc
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    
    TT_RELEASE_SAFELY(_lastDate);
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    
    _fetchedResultsController.delegate = nil;
    
    TT_RELEASE_SAFELY(_fetchedResultsController); 
    TT_RELEASE_SAFELY(_items); 
    TT_RELEASE_SAFELY(_titleView);
    TT_RELEASE_SAFELY(_contentView);  
    TT_RELEASE_SAFELY(_chatContent);  
    TT_RELEASE_SAFELY(_chatInput);     
    TT_RELEASE_SAFELY(_chatBar); 
    TT_RELEASE_SAFELY(_sendButton); 
    TT_RELEASE_SAFELY(_leftBubble);
    TT_RELEASE_SAFELY(_rightBubble);    
    TT_RELEASE_SAFELY(_avatar);    
    TT_RELEASE_SAFELY(_myAvatar); 
    TT_RELEASE_SAFELY(_loadHistoryButton); 
    TT_RELEASE_SAFELY(_clearHistoryButton); 
    TT_RELEASE_SAFELY(_chatHeaderView);  
    TT_RELEASE_SAFELY(_facialButton); 
    TT_RELEASE_SAFELY(_sendfaceArray);
    TT_RELEASE_SAFELY(_receivefaceArray);
    TT_RELEASE_SAFELY(_facialPopover);
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:nil];	                 
    
    
    
    self.navigationController.navigationBarHidden = NO;
    
    self.navigationItem.titleView = self.titleView;
    
    self.leftBubble = [[UIImage imageNamed:@"ChatBubbleGray"] stretchableImageWithLeftCapWidth:23.0f topCapHeight:15.0f];
    self.rightBubble = [[UIImage imageNamed:@"ChatBubbleGreen"] stretchableImageWithLeftCapWidth:15.0f topCapHeight:13.0f];
    
    
}

- (void)viewDidUnload
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    //TT_RELEASE_SAFELY(_fetchedResultsController); 
    //TT_RELEASE_SAFELY(_items); 
    TT_RELEASE_SAFELY(_titleView); 
    TT_RELEASE_SAFELY(_contentView);  
    TT_RELEASE_SAFELY(_chatContent);     
    TT_RELEASE_SAFELY(_chatInput);     
    TT_RELEASE_SAFELY(_chatBar); 
    TT_RELEASE_SAFELY(_sendButton); 
    TT_RELEASE_SAFELY(_leftBubble);
    TT_RELEASE_SAFELY(_rightBubble);  
    TT_RELEASE_SAFELY(_avatar);  
    TT_RELEASE_SAFELY(_myAvatar);
    TT_RELEASE_SAFELY(_loadHistoryButton); 
    TT_RELEASE_SAFELY(_clearHistoryButton); 
    TT_RELEASE_SAFELY(_chatHeaderView);  
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    self.active = YES;
    [self loadMessages];
    [self reloadData];

    [self reloadAvatar];
    
    
	[super viewWillAppear:animated];
    [self.chatContent performSelector:@selector(flashScrollIndicators) withObject:nil afterDelay:0.0];
    [self scrollToBottomAnimated:NO];
    if (!TTIsPad()) {
        [[[XMPPClient sharedInstance]xmppStream] addDelegate: self delegateQueue:dispatch_get_main_queue()];
    }
    
    
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    
    
    [super viewWillDisappear:animated];    
}

- (void)viewDidDisappear:(BOOL)animated
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    self.active = NO;
    if (!TTIsPad()) {
        [[[XMPPClient sharedInstance]xmppStream] removeDelegate:self];
    }
    [super viewDidDisappear:animated];
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
//    if (TTIsPad()) {
//        return YES;
//        
//    } else {
//        return interfaceOrientation == UIInterfaceOrientationPortrait;
//    }
//}

//- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
//{
//
//    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
//    [self reloadData];
//}

//- (void) layoutSubviews
//{
//    
//}

- (void)loadView {
    
    [super loadView];
    
    
    self.titleView = [[[RosterTitleView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 44)] autorelease];
    
    
    self.contentView = [[[UIView alloc] initWithFrame:CGRectMake(0.0f, 
                                                                 0.0f, 
                                                                 self.view.width,
                                                                 self.view.height)] autorelease];    
    _contentView.backgroundColor = CHAT_BACKGROUND_COLOR; // shown during rotation
    _contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
    UIViewAutoresizingFlexibleHeight;
    
    [self.view addSubview:self.contentView];
    
    
    
    
    // Create chatContent.
    self.chatContent = [[[UITableView alloc] initWithFrame:
                         CGRectMake(0.0f, 0.0f, _contentView.frame.size.width,
                                    _contentView.frame.size.height-kChatBarHeight1)] autorelease];
    _chatContent.clearsContextBeforeDrawing = NO;
    _chatContent.delegate = self;
    _chatContent.dataSource = self;
    _chatContent.contentInset = UIEdgeInsetsMake(7.0f, 0.0f, 0.0f, 0.0f);
    _chatContent.backgroundColor = CHAT_BACKGROUND_COLOR;
    _chatContent.separatorStyle = UITableViewCellSeparatorStyleNone;
    _chatContent.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    
    
    [_contentView addSubview:_chatContent];
    
    
    self.chatHeaderView =[[[UIView alloc] initWithFrame:
                           CGRectMake(0.0f, 0.0f, _contentView.frame.size.width,kChatBarHeight1)] autorelease];
    _chatHeaderView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.loadHistoryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _loadHistoryButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleWidth;
    [_loadHistoryButton setTitle:@"载入历史记录" forState: UIControlStateNormal];
    //[loadHistoryButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];    
    [_loadHistoryButton addTarget: self action:@selector(loadHistoryAction) forControlEvents:UIControlEventTouchUpInside];
    [_loadHistoryButton sizeToFit];
    
    CGFloat width = self.contentView.width/2 - 2*kTableCellSmallMargin;
    _loadHistoryButton.frame= CGRectMake(kTableCellSmallMargin, 0, width, _loadHistoryButton.height) ;
    
    [_chatHeaderView addSubview: _loadHistoryButton];
    
    self.clearHistoryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _clearHistoryButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleWidth;
    [_clearHistoryButton setTitle:@"清空聊天记录" forState: UIControlStateNormal];
    //[clearHistoryButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];    
    [_clearHistoryButton addTarget: self action:@selector(clearHistoryAction) forControlEvents:UIControlEventTouchUpInside];
    [_clearHistoryButton sizeToFit];    
    
    _clearHistoryButton.frame= CGRectMake(self.contentView.width/2+kTableCellSmallMargin, 0, width, _clearHistoryButton.height) ;
    
    [_chatHeaderView addSubview: _clearHistoryButton];
    
    
    _chatContent.tableHeaderView = _chatHeaderView;
    
    _chatBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.contentView.height - kChatBarHeight1,
                                                        self.view.width, kChatBarHeight1)];
    _chatBar.clearsContextBeforeDrawing = NO;
    _chatBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin |
    UIViewAutoresizingFlexibleWidth;
    
    
    self.chatInput = [[[HPGrowingTextView alloc] initWithFrame:CGRectMake(46, 3, self.view.width - 80-40, 40)] autorelease];
    _chatInput.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
	_chatInput.minNumberOfLines = 1;
	_chatInput.maxNumberOfLines = 6;
	_chatInput.returnKeyType = UIReturnKeyDefault;
	_chatInput.font = [UIFont systemFontOfSize:15.0f];
	_chatInput.delegate = self;
    _chatInput.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    _chatInput.backgroundColor = [UIColor whiteColor];
    
    [_contentView addSubview:_chatBar];
    
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
    entryImageView.frame = CGRectMake(45, 0, self.view.width - 72-40, 40);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, _chatBar.frame.size.width, _chatBar.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    _chatInput.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // view hierachy
    [_chatBar addSubview:imageView];
    [_chatBar addSubview:_chatInput];
    [_chatBar addSubview:entryImageView];
    
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
	self.sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
	_sendButton.frame = CGRectMake(_chatBar.frame.size.width - 69, 8, 63, 27);
    _sendButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	[_sendButton setTitle:@"发送" forState:UIControlStateNormal];
    
    [_sendButton setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    _sendButton.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
    _sendButton.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    
    [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[_sendButton addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [_sendButton setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [_sendButton setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
    [self resetSendButton];
	[_chatBar addSubview:_sendButton];
    
    
    self.facialButton = [UIButton buttonWithType:UIButtonTypeCustom];
	_facialButton.frame = CGRectMake(3, 8, 40, 27);
    _facialButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
	[_facialButton setImage:[UIImage imageNamed:@"facialButton.png"] forState:UIControlStateNormal];
    _facialButton.tag=0;
    
	[_facialButton addTarget:self action:@selector(sendFacial:) forControlEvents:UIControlEventTouchUpInside];
   	[_chatBar addSubview:_facialButton];
    
}

-(void)sendFacial:(UIButton*)bt
{
    
    if (TTIsPad()) {
        
        _scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,320,45*3)];
        _scrollView.backgroundColor=[UIColor grayColor];
        
        
        CGSize size=CGSizeMake(45, 45);
        
        for (int page=0; page<1; page++) {
            
            UIView *fview=[[UIView alloc] initWithFrame:CGRectMake(2.5+320*page, 0, 320,45*3)];
            
            for (int row=0; row<3; row++) {
                for (int column=0; column<7; column++) {
                    
                    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
                    NSString *imageName=[NSString stringWithFormat:@"%d.png",row*7+column/*+(page*28)*/];
                    [button setBackgroundColor:[UIColor grayColor]];
                    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
                    [button setFrame:CGRectMake(0+column*size.width, 0+row*size.height, size.width, size.height)];
                    [button setTitle:[_sendfaceArray objectAtIndex:(row*7+column/*+(page*28)*/)] forState:UIControlStateNormal];
                    button.tag=row*7+column/*+(page*28)*/;
                    [button addTarget:self action:@selector(selected:) forControlEvents:UIControlEventTouchUpInside];
                    [fview addSubview:button];
                }
            }
            [_scrollView addSubview:fview];
            [fview release];
        }
        _scrollView.contentSize=CGSizeMake(320/**2*/,45*3);
        _scrollView.pagingEnabled=YES;
        

        
        
        UIViewController* popoverContent = [[UIViewController alloc] init];
        popoverContent.view = _scrollView;
        popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 45*3);
        
        _facialPopover = [[UIPopoverController alloc]initWithContentViewController:popoverContent]; 
        [_facialPopover presentPopoverFromRect:_facialButton.frame inView:_chatBar permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        [popoverContent release];
    } else {
        
        [_chatInput becomeFirstResponder];
        
        //    UIView*   aw=[[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 70)];
        //    aw.backgroundColor=[UIColor redColor];
        //    
        //    
        //    // locate keyboard view  
        //    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];//返回应用程序window  
        //    UIView* keyboard;
        //    for(int i=0; i<[tempWindow.subviews count]; i++) //遍历window上的所有subview  
        //    {  
        //        keyboard = [tempWindow.subviews objectAtIndex:i];  
        //        if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) {
        //            [keyboard setFrame:CGRectMake(0,300, 320, 70)];
        //            
        //            [keyboard addSubview:aw];  
        //        }
        //    }  
        
        UIView *foundKeyboard = nil;
        
        UIWindow *keyboardWindow = nil;
        for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) 
        {
            if (![[testWindow class] isEqual:[UIWindow class]]) 
            {
                keyboardWindow = testWindow;
                break;
            }
        }
        if (!keyboardWindow) return;
        
        for (UIView *possibleKeyboard in [keyboardWindow subviews]) 
        {            
            //iOS3
            if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) 
            {
                foundKeyboard = possibleKeyboard;
                break;
            }
            else
            {
                // iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.@"<UIKeyboard" 字串在 iOS4 中也被修正過, 它被藏在 @"<UIPeripheralHostView"裡.
                if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) 
                {
                    possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
                }                                                                                
                
                if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) 
                {
                    foundKeyboard = possibleKeyboard;
                    break;
                }                
            }            
        }
        
        
        bt.tag=!bt.tag;
        if (bt.tag) {
            
            _scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,foundKeyboard.frame.size.width,foundKeyboard.frame.size.height)];
            _scrollView.backgroundColor=[UIColor grayColor];
            
            
            CGSize size=CGSizeMake(45, 45);
            
            for (int page=0; page<1; page++) {
                UIView *fview=[[UIView alloc] initWithFrame:CGRectMake(2.5+foundKeyboard.frame.size.width*page, 0, foundKeyboard.frame.size.width,foundKeyboard.frame.size.height)];
                
                for (int row=0; row<3; row++) {
                    for (int column=0; column<7; column++) {
                        
                        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
                        NSString *imageName=[NSString stringWithFormat:@"%d.png",row*7+column/*+(page*28)*/];
                        [button setBackgroundColor:[UIColor grayColor]];
                        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
                        [button setFrame:CGRectMake(0+column*size.width, 0+row*size.height, size.width, size.height)];
                        [button setTitle:[_sendfaceArray objectAtIndex:(row*7+column/*+(page*28)*/)] forState:UIControlStateNormal];
                        button.tag=row*7+column/*+(page*28)*/;
                        [button addTarget:self action:@selector(selected:) forControlEvents:UIControlEventTouchUpInside];
                        [fview addSubview:button];
                    }
                }
                [_scrollView addSubview:fview];
                [fview release];
            }
            _scrollView.contentSize=CGSizeMake(foundKeyboard.frame.size.width/**2*/,foundKeyboard.frame.size.height);
            _scrollView.pagingEnabled=YES;
        
            if (foundKeyboard) 
            {            
                [foundKeyboard addSubview:_scrollView];
            }
            
            
        }else {
            [_scrollView removeFromSuperview];
            TT_RELEASE_SAFELY(_scrollView);
        }
        

    }
   
    
}

-(void)selected:(UIButton*)bt
{    
    NSString *str=[NSString stringWithFormat:@"%@%@",_chatInput.text,bt.titleLabel.text];
    _chatInput.text=str;    
}


#pragma mark - UIKeyboardNotifications
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
    DDLogVerbose(@"%@: %@ %@", THIS_FILE, THIS_METHOD, note);
    //	CGRect keyboardBeginFrame;
    CGRect keyboardEndFrame;
    //    CGRect keyboardBounds;
    //    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBeginFrame];
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardEndFrame];
    //    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    CGFloat keyboardHeight;
    switch ([UIApplication sharedApplication].statusBarOrientation) {
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
            keyboardHeight = keyboardEndFrame.size.height;
            break;
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
            keyboardHeight = keyboardEndFrame.size.width;
            break;
    }    
    
    
	// get a rect for the textView frame
    //    CGRect viewFrame = self.contentView.frame;
    //    viewFrame.size.height += (keyboardEndFrame.origin.y-keyboardBeginFrame.origin.y);
    //    //viewFrame.size.height -=  keyboardEndFrame.size.height;
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
    
    
	self.contentView.frame =  CGRectMake(0.0f,0.0f,self.view.width, self.view.height-keyboardHeight);
    
	// commit animations
	[UIView commitAnimations];
    
    [self scrollToBottomAnimated:YES];
}

-(void) keyboardWillHide:(NSNotification *)note{
    DDLogVerbose(@"%@: %@ %@", THIS_FILE, THIS_METHOD, note);
    
    //	CGRect keyboardBeginFrame;
    //    CGRect keyboardEndFrame;
    //    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBeginFrame];
    //    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardEndFrame];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
	// get a rect for the textView frame
    //    CGRect viewFrame = self.contentView.frame;
    //    viewFrame.size.height += (keyboardEndFrame.origin.y-keyboardBeginFrame.origin.y);
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	self.contentView.frame = CGRectMake(0.0f, 
                                        0.0f, 
                                        self.view.width,
                                        self.view.height);
    DDLogVerbose(NSStringFromCGRect(self.contentView.frame));
    
	// commit animations
	[UIView commitAnimations];
    [self scrollToBottomAnimated:YES];
}


#pragma mark - HPGrowingTextViewDelegate
- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect chatBarFrame = _chatBar.frame;
    CGRect chatContentFrame = _chatContent.frame;
    chatBarFrame.size.height -= diff;
    chatContentFrame.size.height += diff;
    
    chatBarFrame.origin.y += diff;
    
    
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.1f];
    
    _chatContent.frame = chatContentFrame;
    _chatBar.frame = chatBarFrame;
    
    [UIView commitAnimations];
    
    [self scrollToBottomAnimated:YES];
    
    
    
}

- (void)growingTextViewDidChange:(HPGrowingTextView *)growingTextView
{
    NSString *rightTrimmedText =
    [growingTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (rightTrimmedText.length > 0) {
        [self enableSendButton];
    } else {
        [self disableSendButton];
    }
    
}






#pragma mark - NSFetchedResultsController

- (NSFetchedResultsController *)fetchedResultsController
{
	if (_fetchedResultsController == nil)
	{
		NSManagedObjectContext *moc = [[XMPPClient sharedInstance] managedObjectContext_message];
		
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message"
		                                          inManagedObjectContext:moc];
        
        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:YES];
        NSPredicate *predicate;
        
        if (self.showHistory) {
            predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@ AND jidStr == %@",
                         [[[[XMPPClient sharedInstance] xmppStream]myJID] bare],self.jidStr];
            
        }else{
            predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@ AND jidStr == %@ AND (timestamp >= %@ OR read = %@)",
                         [[[[XMPPClient sharedInstance] xmppStream]myJID] bare],self.jidStr,self.lastDate, [NSNumber numberWithBool:NO]]; 
        }
		
        
		NSArray *sortDescriptors = [NSArray arrayWithObjects:sd, nil];
		
		NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
		[fetchRequest setEntity:entity];
        [fetchRequest setPredicate:predicate];
		[fetchRequest setSortDescriptors:sortDescriptors];
		[fetchRequest setFetchBatchSize:10];
        
		_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:nil cacheName:nil];
		[_fetchedResultsController setDelegate:self];
		[sd release];
		[fetchRequest release];
	}
    return _fetchedResultsController;
}


- (void)fetchMessages
{
    TT_RELEASE_SAFELY(_fetchedResultsController);
    
    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error])
    {
        DDLogWarn(@"Error performing fetch: %@", error);
    }      
}

- (void)loadMessages
{
    [self fetchMessages];
    if (!_showHistory && self.fetchedResultsController.fetchedObjects.count>0) {
        Message* msg= [self.fetchedResultsController.fetchedObjects objectAtIndex:0];
        
        if( [self.lastDate timeIntervalSinceDate:msg.timestamp] > 0){
            self.lastDate = msg.timestamp;
            [self fetchMessages];
        }
        
    }
    
    
}

- (NSUInteger)addMessage:(Message *)message 
{
    // Show sentDates at most every 15 minutes.
    NSDate *currentSentDate = [message timestamp];
    NSUInteger numberOfObjectsAdded = 1;
    NSUInteger prevIndex = [_items count] - 1;
    
    // Show sentDates at most every 15 minutes.
    
    if([_items count])
    {
        BOOL prevIsMessage = [[_items objectAtIndex:prevIndex] isKindOfClass:[Message class]];
        if(prevIsMessage)
        {
            Message * temp = [_items objectAtIndex:prevIndex];
            NSDate * previousSentDate = temp.timestamp;
            // if there has been more than a 15 min gap between this and the previous message!
            if([currentSentDate timeIntervalSinceDate:previousSentDate] > SECONDS_BETWEEN_MESSAGES) 
            { 
                [_items addObject:currentSentDate];
                numberOfObjectsAdded = 2;
            }
        }
    }
    else
    {
        // there are NO messages, definitely add a timestamp!
        [_items addObject:currentSentDate];
        numberOfObjectsAdded = 2;
    }
    
    [_items addObject:message];
    
    return numberOfObjectsAdded;
    
}

- (NSUInteger)removeMessageAtIndex:(NSUInteger)index {
    //    NSLog(@"Delete message from cellMap");
    
    // Remove message from cellMap.
    [_items removeObjectAtIndex:index];
    NSUInteger numberOfObjectsRemoved = 1;
    NSUInteger prevIndex = index - 1;
    NSUInteger itemCount = [_items count];
    
    BOOL isLastObject = index == itemCount;
    BOOL prevIsDate = [[_items objectAtIndex:prevIndex] isKindOfClass:[NSDate class]];
    
    if ((isLastObject && prevIsDate) ||
        (prevIsDate && [[_items objectAtIndex:index] isKindOfClass:[NSDate class]])) {
        [_items removeObjectAtIndex:prevIndex];
        numberOfObjectsRemoved = 2;
    }
    return numberOfObjectsRemoved;
}

- (void)reloadData {
	DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    if(self.active){
        @try {
            
            self.items  = [NSMutableArray array];
            
            for (Message *message in [self.fetchedResultsController fetchedObjects]) {
                [self addMessage:message];
            }
            
            
            [_chatContent reloadData];
            
            
        }
        @catch (NSException *exception) {
            DDLogError(@"Exception: %e", exception);
        }
        @finally {
            
        }
    }
    
}



#pragma mark - NSFetchedResultsControllerDelegate
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
    if(self.active){
        NSArray *indexPaths;
        
        switch(type) {
            case NSFetchedResultsChangeInsert: {
                NSUInteger cellCount = [_items count];
                
                NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:cellCount inSection:0];
                
                if ([self addMessage:anObject] == 1) {
                    //                NSLog(@"insert 1 row at index: %d", cellCount);
                    indexPaths = [[NSArray alloc] initWithObjects:firstIndexPath, nil];
                } else { // 2
                    //                NSLog(@"insert 2 rows at index: %d", cellCount);
                    indexPaths = [[NSArray alloc] initWithObjects:firstIndexPath,
                                  [NSIndexPath indexPathForRow:cellCount+1 inSection:0], nil];
                }
                
                [_chatContent insertRowsAtIndexPaths:indexPaths
                                    withRowAnimation:UITableViewRowAnimationNone];
                [indexPaths release];
                [self scrollToBottomAnimated:YES];
                break;
            }
            case NSFetchedResultsChangeDelete: {
                NSUInteger objectIndex = [_items indexOfObjectIdenticalTo:anObject];
                NSIndexPath *objectIndexPath = [NSIndexPath indexPathForRow:objectIndex inSection:0];
                
                if ([self removeMessageAtIndex:objectIndex] == 1) {
                    //                NSLog(@"delete 1 row");
                    indexPaths = [[NSArray alloc] initWithObjects:objectIndexPath, nil];
                } else { // 2
                    //                NSLog(@"delete 2 rows");
                    indexPaths = [[NSArray alloc] initWithObjects:objectIndexPath,
                                  [NSIndexPath indexPathForRow:objectIndex-1 inSection:0], nil];
                }
                
                [_chatContent deleteRowsAtIndexPaths:indexPaths
                                    withRowAnimation:UITableViewRowAnimationNone];
                [indexPaths release];
                break;
            }
        }
    }
    
}








#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    //    NSLog(@"height for row: %d", [indexPath row]);
    
    NSObject *object = [_items objectAtIndex:[indexPath row]];
    
    // Set SentDateCell height.
    if ([object isKindOfClass:[NSDate class]]) {
        return kSentDateFontSize + 7.0f;
    }
    
    // Set MessageCell height.
    CGFloat messageTextWidth = _chatContent.width / 2;
    CGSize size = [[(Message *)object content] sizeWithFont:[UIFont systemFontOfSize:kMessageFontSize]
                                          constrainedToSize:CGSizeMake(messageTextWidth, CGFLOAT_MAX)
                                              lineBreakMode:UILineBreakModeWordWrap];
    return size.height + 25.0f;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
    //return [[self.fetchedResultsController fetchedObjects] count];
    return [_items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *kChatCell = @"ChatCell";
    UIImageView *msgBackground;
    UITextView *msgText;    
    UIImageView *avatarView;
    UILabel *msgSentDate;
    
    NSObject *object = [_items objectAtIndex:[indexPath row]];
	UITableViewCell *cell;
    
    if ([object isKindOfClass:[NSDate class]]) {
        static NSString *kSentDateCellId = @"SentDateCell";
        cell = [tableView dequeueReusableCellWithIdentifier:kSentDateCellId];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:kSentDateCellId] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            // Create message sentDate lable
            msgSentDate = [[UILabel alloc] initWithFrame:
                           CGRectMake(-2.0f, 0.0f,
                                      _chatContent.frame.size.width, kSentDateFontSize+5.0f)];
            
            
            msgSentDate.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;// UIViewAutoresizingFlexibleWidth;
            msgSentDate.clearsContextBeforeDrawing = NO;
            msgSentDate.tag = SENT_DATE_TAG;
            msgSentDate.font = [UIFont boldSystemFontOfSize:kSentDateFontSize];
            msgSentDate.lineBreakMode = UILineBreakModeTailTruncation;
            msgSentDate.textAlignment = UITextAlignmentCenter;
            msgSentDate.backgroundColor = CHAT_BACKGROUND_COLOR; // clearColor slows performance
            msgSentDate.textColor = [UIColor grayColor];
            //msgSentDate.backgroundColor = [UIColor blueColor];
            [cell addSubview:msgSentDate];
            [msgSentDate release];
        } else {
            msgSentDate = (UILabel *)[cell viewWithTag:SENT_DATE_TAG];
        }
        
        msgSentDate.text = [NSDateFormatter localizedStringFromDate:(NSDate *)object dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle];
        return cell;    
        
        
    }        
    
    cell = [tableView dequeueReusableCellWithIdentifier:kChatCell];
    
	if (cell == nil)
	{
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:kChatCell] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentView.width=_chatContent.width;
        avatarView = [[UIImageView alloc] init];
        avatarView.clearsContextBeforeDrawing = NO;
        avatarView.tag = AVATAR_TAG;
        
        [cell.contentView addSubview:avatarView];
        [avatarView release];
        
        // Create message background image view
        msgBackground = [[UIImageView alloc] init];
        msgBackground.clearsContextBeforeDrawing = NO;
        msgBackground.tag = BACKGROUND_TAG;
        msgBackground.backgroundColor = CHAT_BACKGROUND_COLOR;//[UIColor clearColor]; 
        [cell.contentView addSubview:msgBackground];
        [msgBackground release];
        
        // Create message text label
        msgText = [[UITextView alloc] init];
        
        msgText.editable = NO;
        msgText.contentInset = UIEdgeInsetsMake(-8,-8,-8,-8);
        msgText.scrollEnabled = NO;
        msgText.showsHorizontalScrollIndicator = NO;
        msgText.showsVerticalScrollIndicator = NO;
        
        msgText.clearsContextBeforeDrawing = NO;
        msgText.tag = TEXT_TAG;
        msgText.backgroundColor = [UIColor clearColor];
        //msgText.numberOfLines = 0;
        //msgText.lineBreakMode = UILineBreakModeWordWrap;
        msgText.font = [UIFont systemFontOfSize:kMessageFontSize];
        [cell.contentView addSubview:msgText];
        [msgText release];   
        
	}else{
        avatarView = (UIImageView *)[cell.contentView viewWithTag:AVATAR_TAG];
        msgBackground = (UIImageView *)[cell.contentView viewWithTag:BACKGROUND_TAG];
        msgText = (UITextView *)[cell.contentView viewWithTag:TEXT_TAG];
    }
    
    Message * message=(Message *)object;
	
    CGFloat messageTextWidth = _chatContent.width / 2;
    
    CGSize size = [message.content sizeWithFont:[UIFont systemFontOfSize:kMessageFontSize]
                              constrainedToSize:CGSizeMake(messageTextWidth, CGFLOAT_MAX)
                                  lineBreakMode:UILineBreakModeWordWrap];
    UIImage *bubbleImage;
    
    BOOL  showAvatar = [[NSUserDefaults standardUserDefaults] boolForKey: kShowChatAvatar];
    
    if ([message isOutbound]) { // right bubble
        CGFloat right = _chatContent.width - kTableCellSmallMargin;
        if(showAvatar){
            right -= kAvatarSize;
            avatarView.hidden=NO;
            avatarView.frame = CGRectMake(right, kMessageFontSize+size.height+ 8.0f - kAvatarSize, kAvatarSize, kAvatarSize);
        }else{
            avatarView.hidden =YES;
            avatarView.frame = CGRectZero;
        }
        avatarView.image = self.myAvatar;
        
        
        CGFloat editWidth = _chatContent.editing ? 32.0f : 0.0f;
        msgBackground.frame = CGRectMake(right-size.width-34.0f-editWidth ,
                                         kMessageFontSize-5.0f, size.width+34.0f,
                                         size.height+12.0f);
        
        bubbleImage = self.rightBubble;
        msgText.frame = CGRectMake(right-size.width-24.0f-editWidth,
                                   kMessageFontSize-1.0f, size.width+18.0f, size.height);
        avatarView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        msgBackground.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        msgText.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        
    } else { // left bubble
        CGFloat left = kTableCellSmallMargin;
        if(showAvatar){
            avatarView.hidden=NO;            
            avatarView.frame = CGRectMake(left, kMessageFontSize+size.height+ 8.0f - kAvatarSize, kAvatarSize, kAvatarSize);
            left += kAvatarSize;
        }else{
            avatarView.hidden =YES;
            avatarView.frame = CGRectZero;
        }
        avatarView.image = self.avatar;
        
        msgBackground.frame = CGRectMake(left, kMessageFontSize-5.0f,
                                         size.width+34.0f, size.height+12.0f);
        bubbleImage = self.leftBubble;
        msgText.frame = CGRectMake(left+22.0f, kMessageFontSize-1.0f, size.width+16.0f, size.height);
        avatarView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        msgBackground.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        msgText.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
    }
    msgBackground.image = bubbleImage;
    
    for (int i=0; i<_receivefaceArray.count; i++) {
        
        if ([message isOutbound]) {
            
            NSMutableString*  receivestr = [[[NSMutableString alloc] init] autorelease];
            [receivestr appendString:@" "];
            [receivestr appendString:[_receivefaceArray objectAtIndex:i]];
            [receivestr appendString:@" "];
            
            NSRange suffixRange=[message.content rangeOfString:receivestr];
            
            if (!(suffixRange.location == NSNotFound)) {
                
                NSString* sendstr=[_sendfaceArray objectAtIndex:i];
                message.content =[message.content stringByReplacingOccurrencesOfString:receivestr withString:sendstr];
            }
            
            
        }else{
            
            NSString*  receivestr = [_receivefaceArray objectAtIndex:i];
            
            NSRange suffixRange=[message.content rangeOfString:receivestr];
            
            if (!(suffixRange.location == NSNotFound)) {
                
                NSString* sendstr=[_sendfaceArray objectAtIndex:i];
                message.content =[message.content stringByReplacingOccurrencesOfString:receivestr withString:sendstr];
            }
        }
    }
    //     NSLog(@"%@",message.content);

    
    msgText.text = message.content;
    if (![message hasBeenRead]) { // not read, so save as read
        [[[XMPPClient sharedInstance] messageStorage] readMessage:message];
    }
	return cell;
}





#pragma mark - XMPPStreamDelegate
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    
    DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, presence);
    if([presence.from isEqualToJID:[XMPPJID jidWithString:self.jidStr] options:XMPPJIDCompareBare]){
        
        if (![@"unavailable" isEqualToString:presence.type] ){
            self.titleView.statusLabel.text = presence.status;
            [self.titleView setIntShow:presence.intShow];      
            
        }else{
            [self.titleView setOffline];
        }
        
        
    }
    
	
}

#pragma mark - Actions
- (void)enableSendButton {
    if (_sendButton.enabled == NO) {
        _sendButton.enabled = YES;
        _sendButton.titleLabel.alpha = 1.0f;
    }
}

- (void)disableSendButton {
    if (_sendButton.enabled == YES) {
        [self resetSendButton];
    }
}

- (void)resetSendButton {
    _sendButton.enabled = NO;
    _sendButton.titleLabel.alpha = 0.5f;
}


- (void) closeAction
{
    [self dismissModalViewControllerAnimated:YES];
}

-(void) loadHistoryAction
{
    self.showHistory = YES;
    [self fetchMessages];
    [self reloadData];
    
}

-(void) clearHistoryAction
{
    XMPPJID* jid = [XMPPJID jidWithString:self.jidStr];
    [[XMPPClient sharedInstance] clearMessagesForJID:jid];
    
}

- (void)reloadAvatar{
    XMPPJID* jid = [XMPPJID jidWithString:self.jidStr];
    
    XMPPUserCoreDataStorageObject* user = [[XMPPClient sharedInstance] userForJID:jid];
    
    self.avatar = [[XMPPClient sharedInstance] avatarForJID:jid];
    self.myAvatar = [[XMPPClient sharedInstance] myAvatar];
    
    [self.titleView setAvatarImage: self.avatar];
    
    NSString* name = user.displayName;
    
    if(!TTIsStringWithAnyText(name)){
        name = self.jidStr;
    }
    
    [self.titleView setName:name];
    
    XMPPResourceCoreDataStorageObject *resource =  user.primaryResource;
    
    if (resource){
        [self.titleView setStatus:resource.status];
        [self.titleView setIntShow:resource.intShow];
        
    }else{
        [self.titleView setOffline];
    }
    
}

- (void)scrollToBottomAnimated:(BOOL)animated {
    NSInteger bottomRow = [_items count] - 1;
    if (bottomRow >= 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:bottomRow inSection:0];
        [_chatContent scrollToRowAtIndexPath:indexPath
                            atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}

- (void)clearChatInput
{
    _chatInput.text = @"";
    [_chatInput resignFirstResponder];
}

-(void)sendMessage
{
    NSString *rightTrimmedMessage =
    [_chatInput.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    //    NSLog(@"%@",rightTrimmedMessage);
    
    for (int i=0; i<_receivefaceArray.count; i++) {
        
        NSString* sendstr=[_sendfaceArray objectAtIndex:i];
        NSRange suffixRange=[rightTrimmedMessage rangeOfString:sendstr];
        
        if (!(suffixRange.location == NSNotFound)) {
            //           NSMutableString*  receivestr=[_receivefaceArray objectAtIndex:i];
            NSMutableString*  receivestr = [[[NSMutableString alloc] init] autorelease];
            //            NSMutableString*  receivestr = [[NSMutableString alloc] initWithString:[_receivefaceArray objectAtIndex:i]];
            //            NSString * a=@" ";
            [receivestr appendString:@" "];
            [receivestr appendString:[_receivefaceArray objectAtIndex:i]];
            [receivestr appendString:@" "];
            
            rightTrimmedMessage =[rightTrimmedMessage stringByReplacingOccurrencesOfString:sendstr withString:receivestr];
            
            
        }
    }
    
//        NSLog(@"%@",rightTrimmedMessage);
    
    // Don't send blank messages.
    if (rightTrimmedMessage.length == 0) {
        [self clearChatInput];
        return;
    }
    
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:rightTrimmedMessage];
    
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"type" stringValue:@"chat"];
    [message addAttributeWithName:@"to" stringValue:_jidStr ];
    [message addChild:body];
    
    
    [[[XMPPClient sharedInstance] xmppStream]sendElement:message];
    [self clearChatInput];
    
    [self scrollToBottomAnimated:YES];
    
}

- (void) setShowHistory:(BOOL)showHistory
{
    _showHistory = showHistory;
    if(showHistory){
        _loadHistoryButton.hidden = YES;
        _clearHistoryButton.frame = CGRectMake(kTableCellSmallMargin, 0, self.contentView.width-2*kTableCellSmallMargin, _clearHistoryButton.height);
    }else{
        _loadHistoryButton.hidden = NO;
        _clearHistoryButton.frame = CGRectMake(self.contentView.width/2+kTableCellSmallMargin, 0, self.contentView.width/2 - 2*kTableCellSmallMargin, _clearHistoryButton.height);        
    }
}

- (void) setJidStr:(NSString *)jidStr
{
    [_jidStr release];
    _jidStr = [jidStr copy];
    self.showHistory = NO;
    [self fetchMessages];
    [self reloadData];  
    [self reloadAvatar];
    
    
    
}

- (void)handleSettingsChanged:(NSNotification *)notification
{
    [self reloadData];
}


@end
